package com.abapi.pay.admin.service.impl;

import com.abapi.cloud.socket.pojo.TcpSession;
import com.abapi.pay.admin.data.ClientData;
import com.abapi.pay.admin.data.ClientInfo;
import com.abapi.pay.admin.service.AbstractEndpointService;
import com.abapi.pay.core.annotation.EndpointMapping;
import com.abapi.pay.core.constans.MessageType;
import com.abapi.pay.core.dto.AbstractBody;
import com.abapi.pay.core.dto.MessageDTO;
import com.abapi.pay.core.dto.RegisterDTO;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author ldx
 * @Date 2019/11/1 15:01
 * @Description
 * @Version 1.0.0
 */
@Service
@EndpointMapping(value = MessageType.REGISTER,desc = "客户端注册")
public class RegisterServiceImpl implements AbstractEndpointService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void handler(TcpSession session, MessageDTO<AbstractBody> messageDTO) {
        RegisterDTO dto = (RegisterDTO) messageDTO.getBody();
        System.out.println("----------------接受到 注册----------");
        System.out.println(JSON.toJSONString(messageDTO));
        logger.info("ip:{},projectName:{},className:{}",session.channel().remoteAddress(),dto.getProjectName(),dto.getClassName());

        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setIp(session.channel().remoteAddress().toString());
        clientInfo.setProjectName(dto.getProjectName());
        clientInfo.setTcpSession(session);
        clientInfo.setClassName(dto.getClassName());
        ClientData.session.put(session.id().asLongText(),clientInfo);

        List<ClientInfo> clientInfos = ClientData.clientData.get(dto.getProjectName());
        if(clientInfos == null || clientInfos.size() <= 0){
            clientInfos = Lists.newArrayList();
        }
        clientInfos.add(clientInfo);
        ClientData.clientData.put(dto.getProjectName(),clientInfos);
    }
}
